<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>百度搜索联想</title>
  <style>
      body {
          display: flex;
          justify-content: center;
          align-items: center;
          height: 500px;
      }

      #search {
          width: 300px;
          height: 30px;
          border: 1px solid #ccc;
          border-radius: 5px;
          padding: 0 10px;
      }
  </style>
</head>
<body>
<div class="baidu">
  <input id="search" placeholder="百度联想搜索" type="text">
  <div class="search-result"
       style="display: none; position: absolute; width: 320px; height: 300px; background-color: #fff; border: 1px solid #ccc; overflow: auto;">
    <ul id="search-result-list"></ul>
  </div>
</div>
</body>
<script>
  let search = document.getElementById('search');
  let searchResultList = document.getElementById('search-result-list');
  let searchResult = document.getElementsByClassName('search-result')[0];
  let searchResultListLi = document.getElementsByTagName('li');
  let searchResultListLiLength = searchResultListLi.length;

  // 模拟数据
  let data = ["JavaScript入门到放弃", "Java程序设计", "Vue.js实战教程", "React实战教程"]

  // 搜索框输入事件
  search.onkeyup = function () {
    //   显示搜索结果
    searchResult.style.display = "block";

    let keyWord = search.value;
    let str = ""
    data.forEach(item => {
      let res = item.indexOf(keyWord);
      if (res !== -1) {
        str += `<li>${item}</li>`
      }
    })
    if (!keyWord || str === "") {
      str = `<li>没有搜索结果</li>`
      searchResultList.innerHTML = str;
    } else {
      searchResultList.innerHTML = str;
    }

  }
  search.onblur = function () {
    searchResult.style.display = "none";
  }


</script>

</html>